(ns samber.services.user.register
  (:require
    [toucan.db :as db]
    [honeysql.core :as sql]
    [samber.db.models :as models]
    [java-time :as time]
    [clojure.tools.logging :as log]
    [samber.config :refer [env]]
    [promesa.exec :as exec]
    [cuerdas.core :as str]
    [samber.middleware.exception :as exception]
    [clj-http.client :as client]
    [samber.services.http-request :as http-service]
    [buddy.hashers :as hashers]))

(defn- check-before-register [user]
  ;; check password
  (if (not= (:password user) (:password-confirmation user))
    (throw (ex-info "check" {:type ::exception/check :msg "password not match!"})))

  ;; check mobile exist
  (if (db/exists? models/User :mobile (:mobile user))
    (throw (ex-info "check" {:type ::exception/check :msg "mobile already exists!"})))

  ;; check user exists
  (if (db/exists? models/User :username (:username user))
    (throw (ex-info "check" {:type ::exception/check :msg "user already exists!"})))

  ;; check sms
  (let [{:keys [mobile code]} user
        params {:phone mobile :code code}]
    (http-service/execute :post "http://localhost:3000/api/check" params)))

(defn register [user]
  (check-before-register user)
  (let [{:keys [username email mobile]} user
        password (hashers/derive (:password user))
        model {:username username
               :email email
               :mobile mobile
               :encrypted_password password}]
    (db/insert! models/User model)))
